from models.todo import Todo
from utils import redirect, template, http_response, json_response


def all(request):
    todo_list = Todo.all()
    todos = [t.json() for t in todo_list]
    return json_response(todos)


def add(request):
    # 原来：
    # form = request.form()
    # Todo.new(form)
    # return redirect('/todo/index')
    # 现在ajax：
    form = request.json()
    t = Todo.new(form)
    return json_response(t.json())


def delete(request):
    # uname = current_user(request)
    # u = User.find_by(username=uname)
    # if u is None:
    #     return redirect('/login')
    # todo_id = int(request.query.get('id', -1))
    todo_id = int(request.query.get('id'))
    # t = Todo.find_by(id=todo_id)
    # if t.user_id != u.id:
    #     return redirect('/login')
    # if t is not None:
    #     t.remove()
    t = Todo.delete(todo_id)
    # return redirect('/todo/index')
    return json_response(t.json())


# def edit(request):
#     # headers = {
#     #     'Content-Type': 'text/html',
#     # }
#     # uname = current_user(request)
#     # u = User.find_by(username=uname)
#     # if u is None:
#     #     return redirect('/login')
#     todo_id = int(request.query.get('id', -1))
#     t = Todo.find_by(id=todo_id)
#     # if t.user_id != u.id:
#     #     return redirect('/login')
#     # body = template('todo_edit.html')
#     # body = body.replace('{{todo_id}}', str(t.id))
#     # body = body.replace('{{todo_title}}', str(t.title))
#     body = template('todo_edit.html', todo=t)
#     # header = response_with_headers(headers)
#     # r = header + '\r\n' + body
#     # return r.encode(encoding='utf-8')
#     return http_response(body)


def update(request):
    # todo_id = int(request.query.get('id'))
    # form = request.form()
    # t = Todo.find_by(id=todo_id)
    # t.task = form.get('task')
    # t.save()
    # return redirect('/todo/index')
    form = request.json()
    todo_id = int(form.get('id'))
    t = Todo.update(todo_id, form)
    return json_response(t.json())


route_dict = {
    '/api/todo/all': all,
    '/api/todo/add': add,
    '/api/todo/delete': delete,
    '/api/todo/update': update,
}
